package services;

import helpers.StringHelper;
import helpers.TranslateHelper;

import java.io.IOException;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import admin.models.CategoryModel;

import com.google.gson.Gson;

import debugs.CategoryDebug;

import entities.Category;

@SuppressWarnings("serial")
public class SubmitCategoryService extends HttpServlet {
	public void doPost(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		response.setContentType("text/html");
		
		String params = (String) request.getParameter("data");
		String sl = (String) request.getParameter("sl");
		String tl = (String) request.getParameter("tl");
		
		Map<String, String> data = new Gson().fromJson(params, Map.class);
		
		CategoryModel categoryModel = CategoryModel.getInstance();
		
		for (Map.Entry<String, String> entry : data.entrySet()) {
			String id = entry.getKey();
			String name = entry.getValue();
			Category category = categoryModel.getCategory(id);
			if (category == null) {
				category = new Category();
				category.setId(id);
				
				if (sl != null && tl != null && !sl.equalsIgnoreCase(tl)) {
					name = TranslateHelper.translate(name, sl, tl);
				}
				
				String alias = StringHelper.replace(name);
				
				category.setName(name);
				category.setAlias(alias);
				categoryModel.insert(category);
			} else {
				System.out.println("category has been exists.");
			}
		}
		
	}
}
